package com.jdk.demo.fileChannel.write;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Test1_3 {
	
	private static FileOutputStream fosRef;
	private static FileChannel fileChannel;

	// 验证write方法是同步的
	// 一共写入20个字符串，字符串之间或者其自身之间是随机添加的，但是字符串"abcde"和"我是中国人"之间或者其自身之间不会出现交叉情况，例如"abc我是de中国人"
	public static void main(String[] args) throws Exception {
		fosRef = new FileOutputStream("a.txt");
		fileChannel = fosRef.getChannel();
		
		for (int i = 0; i < 10; i++) {
			Thread thread1 = new Thread(){
				@Override
				public void run(){
					try{
						ByteBuffer buffer1 = ByteBuffer.wrap("abcde\r\n".getBytes());
						fileChannel.write(buffer1);
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			};
			Thread thread2 = new Thread(){
				@Override
				public void run(){
					try{
						ByteBuffer buffer1 = ByteBuffer.wrap("我是中国人\r\n".getBytes());
						fileChannel.write(buffer1);
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			};
			thread1.start();
			thread2.start();
		}
		
		Thread.sleep(3000);
		fileChannel.close();
		fosRef.close();
	}
	
}
